<?php

namespace App\Kuafu\Pay\Command;

use App\Kuafu\Pay\Model\PayStreamMappingModel;
use App\Kuafu\Pay\Model\PayStreamModel;
use Illuminate\Console\Command;

class RollbackPayStreamSplit extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'pay:rollback-pay-stream-split';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '回滚payStream分表信息';

    /**
     * Create a new command instance.
     *
     * @return void//
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command
     *
     * @return int
     */

    public function handle()
    {
        @ini_set('memory_limit', '-1');

        PayStreamMappingModel::query()
                             ->where('createdAt', '>=', strtotime("2022-08-25 06:00:00"))
                             ->chunk(100, function ($streams) {

                                 $addData = [];

                                 $streams->each(function ($item) use (&$addData) {
                                     $pay = PayStreamModel::suffix($item->shopId, $item->sysType)
                                                          ->where('payNo', $item->payNo)
                                                          ->first();

                                     if (!PayStreamModel::suffix(null)
                                                        ->where('payNo', $item->payNo)
                                                        ->selectRaw(1)
                                                        ->first()) {

                                         $addData[] = $pay->toArray();

                                         $this->info("payNo:{$item->payNo} shopId:{$item->shopId} sysType:{$item->sysType} createdAt:".date('Y-m-d H:i:s', $item->createdAt));
                                     }
                                 });

                                 if ($addData) {
                                     PayStreamModel::suffix(null)->insert($addData);
                                 }
                             });

    }

}
